<script lang="ts" setup>

import {onMounted, reactive, ref} from 'vue';
import {post, get} from '../utils/axios-request'
import router from '../router'
import {ElNotification} from 'element-plus'

/**
 * 获取作品数据
 */
interface Option {
  id: string
  name: string
  author: string
  label: string
  thumbnail: string
}

const types = ref([]);
const pricePeriods = ref([]);
const param = reactive({
  text: null,
  type: null,
  sellStatus: null,
  pricePeriod: null
})

const getArtworks = () => {
  post('/pdf/export/get/artworks', param, (list) => {
    artworks.value = list.map(item => {
      item.label = `【${item.author}】${item.name}`;
      return item;
    });
    selectLoading.value = false;
  })
}

const artworks = ref<Option[]>()

const form = reactive({
  title: '',
  artworks: [],
  remarks: ''
})

const getSelectors = async (): Promise<void> => {

  get('/public/data/selectors/ARTWORK_TYPE', (res) => {
    types.value = res;
  })
  get('/public/data/selectors/PRICE_PERIOD', (res) => {
    pricePeriods.value = res;
  })

}

const onChangeTypes = (type: number) => {
  param.type = type;
}

const onChangePricePeriods = (pricePeriod: number) => {
  console.log(pricePeriod)
  param.pricePeriod = pricePeriod;
}

const onChangeCellStatus = (cellStatus: number[]) => {
  param.sellStatus = cellStatus;
}

const selectLoading = ref(false);
const filterArtworks = (query: string) => {
  selectLoading.value = true;
  param.text = query;
  getArtworks();
}

const isOptionDisabled = (value: string) => {
  // 如果已选中数量 >= 最大限制，且当前选项未被选中，则禁用
  return (
      form.artworks.length > 19 && !form.artworks.includes(value)
  );
}

/**
 * 生命周期钩子
 */
onMounted(() => {
  getSelectors();
  getArtworks();
})

/**
 * form提交
 */

const submitLoading = ref(false);
const buttonLabel = ref('创建导出');
const savePdfExport = () => {

  if (!form.title) {
    ElNotification({
      title: 'Error',
      message: '导出标题不能为空',
      duration: 1500,
      type: 'error'
    });
    return;
  }
  if (!form.artworks || form.artworks.length === 0) {
    ElNotification({
      title: 'Error',
      message: '作品列表不能为空',
      duration: 1500,
      type: 'error'
    })
    return;
  } else {
    if (form.artworks.length > 20) {
      ElNotification({
        title: 'Error',
        message: '作品不能超过20件',
        duration: 1500,
        type: 'error'
      })
      return;
    }
  }
  submitLoading.value = true;
  buttonLabel.value = '首次生成PDF时间较长，请耐心等待...';
  post('/pdf/export/save', form, () => {
    ElNotification({
      title: 'Success',
      message: '创建成功！',
      type: 'success',
      duration: 1000,
      onClose: () => {
        router.push('/export/list')
      }
    })
  }, (message: string) => {
    ElNotification({
      title: 'Error',
      message: message,
      duration: 1500,
      type: 'error'
    })
    submitLoading.value = false;
    buttonLabel.value = '创建导出';
  });
}
</script>

<template>
  <div class="form-container">
    <el-form :model="form" label-width="auto" style="width: 70% ">
      <h2>新建导出</h2>
      <el-form-item label="标题" required prop="title" :rules="{required: true, message: '标题不能为空'}">
        <el-input v-model="form.title" placeholder="为这个导出起一个标题"/>
      </el-form-item>
      <el-form-item label="作品类型">
        <el-row style="width: 100%">
          <el-col :span="60">
            <el-radio-group v-model="param.type" size="small" @change="onChangeTypes">
              <el-radio-button :value="null">×</el-radio-button>
              <el-radio-button v-for="type in types" :value="type.value">{{ type.label }}</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="价格范围">
        <el-row style="width: 100%">
          <el-col :span="60">
            <el-radio-group v-model="param.pricePeriod" @change="onChangePricePeriods">
              <el-radio-button :value="null">×</el-radio-button>
              <el-radio-button v-for="period in pricePeriods" :value="period.value">{{ period.label }}</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="售卖状态">
        <el-row style="width: 100%">
          <el-col :span="60">
            <el-radio-group v-model="param.sellStatus" @change="onChangeCellStatus">
              <el-radio-button :value="null">×</el-radio-button>
              <el-radio-button :value="true">已售</el-radio-button>
              <el-radio-button :value="false">未售</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="选择作品" required>
        <el-select
            v-model="form.artworks"
            filterable
            placeholder="请选择作品"
            multiple
            clearable
            :filter-method="filterArtworks"
            no-data-text="暂无作品"
            aria-valuemax="5"
            loading-text="作品加载中"
            :loading="selectLoading"
        >
          <el-option class="artwork-option" v-for="option in artworks"
                     :key="option.id" :value="option.id" :label="option.label"
                     :disabled="isOptionDisabled(option.id)">
            <span style="float: left">{{ option.label }}</span>
            <el-image class="option-image" :src="option.thumbnail"></el-image>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注/说明">
        <el-input
            v-model="form.remarks"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="对当前导出进行补充和说明"
        />
      </el-form-item>
      <div class="button-div">
        <el-button class="large-button"
                   plain
                   size="large"
                   type="primary"
                   @click="savePdfExport"
                   :loading="submitLoading">
          {{ buttonLabel }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.large-button {
  width: 80%;
}

.button-div {
  /* 使用 Flexbox 让按钮居中 */
  display: flex;
  justify-content: center; /* 水平居中 */
  gap: 10px; /* 按钮之间的间距 */
}

h2 {
  margin-top: 2vh;
  font-weight: 200;
}

.option-image {
  width: 80px;
  float: right;
  margin-right: 30px
}

.artwork-option {
  height: 100px;
  margin-bottom: 10px;
  line-height: 90px
}
</style>